import axios from "axios";


import storage from "./storege.js";
import router from "../router/index";
const http = axios.create({
  timeout: 2000, //超时断开连接
  baseURL: "/api", //配置根路径
});

//拦截请求，设置请求头信息
http.interceptors.request.use((req) => {
  let token = storage.getStorage("token");
  token && (req.headers.token = token);
  return req;
});
//拦截响应头，获取响应头里的token保存至本地缓存
http.interceptors.response.use((res) => {
  res.headers.token && storage.setStorage("token", res.headers.token);
  return res;
}),
  (err) => {
    let resp = err.response;
    switch (resp.status) {
      case 401:
        alert("身份已过期，请重新登录");
        storage.removeStorage("token");
        storage.removeStorage("userName");
        storage.removeStorage("userId");
        router.push("/login");
        break;
      case 500:
        alert("服务器报错");
        break;
      case 404:
        alert("请求未找到");
        break;
    }
    return Promise.reject(err.response.data);
  };
export default http;
